#region Using Directives

using System;
using Eneta.Portal.Common;
using Eneta.Portal.Forum.Common.Data;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Eneta.Portal.Forum.Core.Service.Application;

#endregion

namespace Eneta.Portal.Forum.Core.Data
{
    public class MessageMapper
    {
        /// <summary>
        /// Creates the domain object.
        /// </summary>
        /// <param name="listItem">The list item.</param>
        /// <returns></returns>
        public static Message CreateDomainObject(SharePointListItem listItem)
        {
            int itemId;
            int.TryParse(listItem["TopicID"], out itemId);
            Logger.LogInfo("MessageMapper.CreateDomainObject: " + listItem["TopicID"], "");
            Message message = new Message(Convert.ToInt32(listItem["TopicID"]));

            message.Name = listItem["Title"];
            if (listItem["UserID"] != null)
            {
                int userId;
                int.TryParse(listItem["UserID"], out userId);
                message.UserId = userId;
            }
            message.Author = RepositoryRegistry.ForumUserRepository.GetBySharePointId(message.UserId);
            message.Created = Convert.ToDateTime(listItem["Created"]);
            message.Modified = Convert.ToDateTime(listItem["Modified"]);
            message.Body = listItem["Body"];
            var forumId = 0;
            if (listItem["ForumID"] != null)
                int.TryParse(listItem["ForumID"], out forumId);
            message.ForumId = forumId;
            message.Id = listItem.Id;

            return message;
        }

        /// <summary>
        /// Creates the dto.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static SharePointListItem CreateDto(Message message)
        {
            string[] postValues = {
                                      "Title", message.Name,
                                      "TopicID", message.TopicId.ToString(),
                                      "ForumID", message.ForumId.ToString(),
                                      "Body", message.Body,
                                      "UserID", message.UserId.ToString(),
                                      "Author", ForumApplication.Instance.CurrentUser.ToString()
                                  };

            return new SharePointListItem(message.Id, postValues);
        }
    }
}